package com.softeware.dao.message;

import com.softeware.dao.BaseDao;
import com.softeware.pojo.Message;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Vector;

public class MessageDaoImpl implements MessageDao {
    @Override
    public List<Message> getAllMessages(Connection connection) throws SQLException {
        PreparedStatement pstm = null;
        ResultSet rs = null;
        Message message = null;
        List<Message> messages = new Vector<>();
        if(connection!=null){
            String sql = "select * from messages";
            Object[] params={};
            rs = BaseDao.execute(connection,pstm,rs,sql,params);
            while(rs.next()){
                message = new Message(
                        rs.getString("author"),
                        rs.getString("subject"),
                        rs.getString("content")
                );
                messages.add(message);
            }
            BaseDao.closeResource(null,pstm,rs);
        }
        return messages;
    }

    @Override
    public List<Message> getMessages(int begin, int quantity) {
        return null;
    }

    @Override
    public int addMessages(Connection connection,Message message) throws SQLException {
        int flag = 0;
        PreparedStatement pstm = null;
        if(connection!=null){
            String sql = "insert into messages (author,subject,content) values (?,?,?)";
            Object[] params = {message.getAuthor(),message.getSubject(),message.getContent()};
            flag = BaseDao.execute(connection,pstm,sql,params);
            BaseDao.closeResource(null,pstm,null);
        }
        return flag;
    }
}
